<template>
  <div class="image-analysis">
    <div class="page-header">
      <h2>OsteoMaster - 影像分析系统</h2>
      <p>上传X光影像进行骨科分析和测量</p>
    </div>

    <div class="content-wrapper">
      <!-- 左侧标注工具面板 -->
      <div class="tools-panel">
        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>标注工具</span>
            </div>
          </template>

          <div class="annotation-tools">
            <el-button-group>
              <el-button :type="activeTool === 'point' ? 'primary' : ''" @click="setTool('point')">
                <el-icon>
                  <Aim />
                </el-icon>
                标点
              </el-button>
              <el-button :type="activeTool === 'line' ? 'primary' : ''" @click="setTool('line')">
                <el-icon>
                  <Minus />
                </el-icon>
                画线
              </el-button>
              <el-button :type="activeTool === 'angle' ? 'primary' : ''" @click="setTool('angle')">
                <el-icon>
                  <Compass />
                </el-icon>
                量角
              </el-button>
              <el-button :type="activeTool === 'connect' ? 'primary' : ''" @click="setTool('connect')">
                <el-icon>
                  <Connection />
                </el-icon>
                智能连角
              </el-button>
            </el-button-group>

            <!-- 智能连接提示信息 -->
            <div v-if="activeTool === 'connect'" class="connect-tip">
              <div class="tip-content">
                <el-icon>
                  <InfoFilled />
                </el-icon>
                <span>连接2个点成线，连接3个点成角</span>
              </div>
              <div v-if="selectedPoints.length > 0" class="selected-points">
                已选择: {{ selectedPoints.length }} 个点
                <el-button size="small" text @click="clearSelectedPoints">
                  <el-icon>
                    <Close />
                  </el-icon>
                  清除
                </el-button>
              </div>
            </div>

            <div class="tool-options">
              <div class="color-picker">
                <label>标注颜色：</label>
                <el-color-picker v-model="annotationColor" size="small" />
              </div>
              <div class="line-width">
                <label>线条粗细：</label>
                <el-input-number v-model="lineWidth" :min="1" :max="10" size="small" />
              </div>
            </div>

            <div class="annotation-info" v-if="annotations.length > 0">
              <div class="info-title">标注统计</div>
              <div class="info-item">
                <span>总数：{{ annotations.length }}</span>
              </div>
              <div class="info-item">
                <span>点：{{annotations.filter(a => a.type === 'point').length}}</span>
              </div>
              <div class="info-item">
                <span>线：{{annotations.filter(a => a.type === 'line').length}}</span>
              </div>
              <div class="info-item">
                <span>角度：{{annotations.filter(a => a.type === 'angle').length}}</span>
              </div>
            </div>


            <div class="export-actions">
              <el-button size="small" type="primary" @click="exportAnnotations" :disabled="annotations.length === 0">
                <el-icon>
                  <Download />
                </el-icon>
                导出标注
              </el-button>
            </div>
          </div>
        </el-card>

        <!-- MPTA测量 -->
        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>MPTA测量</span>
            </div>
          </template>

          <div class="mpta-controls">
            <div class="mpta-actions">
              <el-button size="small" type="primary" @click="startMPTAMeasurement">
                <el-icon>
                  <Plus />
                </el-icon>
                开始MPTA测量
              </el-button>
            </div>

            <div v-if="mptaMeasurements.length > 0" class="mpta-list">
              <div class="mpta-header">
                <span>测量结果 ({{ mptaMeasurements.length }})</span>
              </div>

              <div v-for="(mpta, index) in mptaMeasurements" :key="mpta.id" class="mpta-item"
                :class="{ active: selectedMPTA && selectedMPTA.id === mpta.id }" @click="selectedMPTA = mpta">
                <div class="mpta-info">
                  <span class="mpta-label">MPTA #{{ index + 1 }}</span>
                  <span class="mpta-value">{{ mpta.angle.toFixed(1) }}°</span>
                </div>
                <el-button size="small" text type="danger" @click.stop="deleteMPTA(mpta.id)">
                  <el-icon>
                    <Delete />
                  </el-icon>
                </el-button>
              </div>
            </div>

            <div v-else class="mpta-empty">
              <p>请先绘制角度来创建MPTA测量</p>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 中间影像显示区域 -->
      <div class="image-viewer">
        <el-card class="viewer-card">
          <template #header>
            <div class="viewer-header">
              <span>影像分析工作台</span>
              <div class="viewer-controls">
                <el-button-group size="small">
                  <el-button @click="openFileExplorer">
                    <el-icon>
                      <Folder />
                    </el-icon>
                    导入影像
                  </el-button>
                  <el-button @click="resetAdjustments">
                    <el-icon>
                      <RefreshLeft />
                    </el-icon>
                    重置
                  </el-button>
                  <el-button size="small" @click="undoLastAction" :disabled="annotations.length === 0">
                    <el-icon>
                      <RefreshLeft />
                    </el-icon>
                    撤销
                  </el-button>
                  <el-button size="small" @click="redoLastAction" :disabled="annotationHistory.length === 0">
                    <el-icon>
                      <RefreshRight />
                    </el-icon>
                    重做
                  </el-button>

                  <el-button type="primary" @click="saveAdjustedImage">
                    <el-icon>
                      <Download />
                    </el-icon>
                    保存
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <div class="canvas-container" ref="canvasContainer">
            <canvas ref="imageCanvas" class="image-canvas" @mousedown="startDrawing" @mousemove="drawing"
              @mouseup="stopDrawing"></canvas>

            <div v-if="!imageLoaded" class="empty-state">
              <el-icon class="empty-icon">
                <Picture />
              </el-icon>
              <p>请导入X光影像开始分析</p>

              <!-- 集成的拖拽上传区域 -->
              <div class="integrated-upload">
                <el-upload class="upload-demo" drag :auto-upload="false" :on-change="handleFileChange"
                  :before-upload="beforeUpload" accept="image/*">
                  <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                  <div class="el-upload__text">
                    将X光影像拖到此处，或<em>点击上传</em>
                  </div>
                  <template #tip>
                    <div class="el-upload__tip">
                      支持JPG、PNG、DICOM格式，文件大小不超过50MB
                    </div>
                  </template>
                </el-upload>
              </div>

              <div class="test-actions">
                <el-button type="primary" @click="loadTestImage">
                  <el-icon>
                    <Picture />
                  </el-icon>
                  加载测试图像
                </el-button>
              </div>
            </div>
          </div>

          <div class="viewer-status">
            <span>坐标: ({{ mouseX }}, {{ mouseY }})</span>
            <span>缩放: {{ Math.round(scale) }}%</span>
            <span v-if="imageLoaded">尺寸: {{ imageWidth }} × {{ imageHeight }}</span>
            <span v-if="annotations.length > 0">标注: {{ annotations.length }} 个</span>
          </div>
        </el-card>

        <!-- 悬浮调整球 -->
        <div class="floating-adjustment" :class="{ expanded: adjustmentExpanded, dragging: floatBallDragging }"
          :style="{ top: floatBallPosition.y + 'px', right: 'auto', left: floatBallPosition.x + 'px' }">
          <div class="float-trigger" @click="toggleAdjustment" @mousedown="startDragFloatBall">
            <el-icon>
              <Setting />
            </el-icon>
          </div>

          <div class="adjustment-panel-floating" v-show="adjustmentExpanded">
            <div class="adjustment-header">
              <span>影像调整</span>
              <el-button size="small" text @click="toggleAdjustment">
                <el-icon>
                  <Close />
                </el-icon>
              </el-button>
            </div>

            <div class="adjustment-controls">
              <div class="control-group">
                <label>亮度: {{ brightness }}</label>
                <el-slider v-model="brightness" :min="-100" :max="100" @input="applyImageAdjustments" />
              </div>
              <div class="control-group">
                <label>对比度: {{ contrast }}</label>
                <el-slider v-model="contrast" :min="-100" :max="100" @input="applyImageAdjustments" />
              </div>
              <div class="control-group">
                <label>饱和度: {{ saturation }}</label>
                <el-slider v-model="saturation" :min="-100" :max="100" @input="applyImageAdjustments" />
              </div>
              <div class="control-group">
                <label>伽马: {{ (gamma / 100 + 1).toFixed(2) }}</label>
                <el-slider v-model="gamma" :min="-50" :max="100" @input="applyImageAdjustments" />
              </div>
              <div class="control-group">
                <label>缩放: {{ scale }}%</label>
                <el-slider v-model="scale" :min="10" :max="500" @input="applyScaleAdjustment" />
              </div>

              <div class="view-controls">
                <el-button-group size="small">
                  <el-button size="small" @click="fitToWindow">
                    <el-icon>
                      <FullScreen />
                    </el-icon>
                    适合窗口
                  </el-button>
                  <el-button size="small" @click="actualSize">
                    <el-icon>
                      <ScaleToOriginal />
                    </el-icon>
                    实际大小
                  </el-button>
                </el-button-group>
              </div>

              <div class="control-group">
                <label>旋转: {{ rotation }}°</label>
                <el-slider v-model="rotation" :min="-180" :max="180" :step="1" @input="applyImageAdjustments" />
              </div>

              <div class="rotation-controls">
                <el-button-group size="small">
                  <el-button @click="rotateLeft">
                    <el-icon>
                      <RefreshLeft />
                    </el-icon>
                    左旋转
                  </el-button>
                  <el-button @click="rotateRight">
                    <el-icon>
                      <RefreshRight />
                    </el-icon>
                    右旋转
                  </el-button>
                </el-button-group>
              </div>

              <div class="flip-controls">
                <el-checkbox v-model="flipHorizontal" @change="applyImageAdjustments">水平翻转</el-checkbox>
                <el-checkbox v-model="flipVertical" @change="applyImageAdjustments">垂直翻转</el-checkbox>
              </div>

              <div class="preset-buttons">
                <el-button size="small" @click="applyPreset('bone')">骨科模式</el-button>
                <el-button size="small" @click="applyPreset('soft')">软组织模式</el-button>
                <el-button size="small" @click="applyPreset('enhance')">增强模式</el-button>
              </div>
            </div>
          </div>
        </div>
      </div>

    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { useStore } from '../../store'
import {
  UploadFilled,
  Folder,
  Aim,
  Minus,
  Compass,
  Delete,
  RefreshLeft,
  RefreshRight,
  FullScreen,
  ScaleToOriginal,
  Picture,
  InfoFilled,
  Download,
  Menu,
  View,
  Plus,
  Setting,
  Close,
  Connection,
  Share
} from '@element-plus/icons-vue'

// 全局状态
const store = useStore()

// 响应式数据
const brightness = ref(0)
const contrast = ref(0)
const saturation = ref(0)
const gamma = ref(0)
const scale = ref(100)
const rotation = ref(0)
const flipHorizontal = ref(false)
const flipVertical = ref(false)
const activeTool = ref('point')
const annotationColor = ref('#ff0000')
const lineWidth = ref(2)
const imageLoaded = ref(false)
const mouseX = ref(0)
const mouseY = ref(0)
const imageWidth = ref(0)
const imageHeight = ref(0)
const originalImageData = ref(null)
const currentImageData = ref(null)

// 标注相关数据
const annotations = ref([])
const isDrawing = ref(false)
const currentAnnotation = ref(null)
const tempPoints = ref([])
const annotationHistory = ref([])
const selectedAnnotation = ref(null)
const isDragging = ref(false)
const dragStartPoint = ref(null)
const dragPointIndex = ref(-1)
const previousTool = ref('point') // 记录切换到选择模式前的工具
// 添加一个全局变量来存储冻结的点位置
const frozenPoints = ref([])

// 连接标记点相关数据
const selectedPoints = ref([])  // 选中的标记点数组
const connectingMode = ref(false)  // 是否处于连接模式

// 视图控制
const showGrid = ref(false)           // 显示网格
const showCenterLine = ref(true)      // 显示中间标线
const showMeasurements = ref(true)    // 显示测量结果
const showMPTA = ref(true)            // 显示MPTA测量

// 悬浮调整球控制
const adjustmentExpanded = ref(false) // 悬浮球展开状态
const floatBallDragging = ref(false)  // 悬浮球拖拽状态
const dragHappened = ref(false) // 标记是否发生了拖拽
const floatBallPosition = ref({ x: window.innerWidth - 100, y: 20 }) // 悬浮球位置（右上角）
const dragStartPos = ref({ x: 0, y: 0 }) // 拖拽开始位置
const dragStartBallPos = ref({ x: 0, y: 0 }) // 拖拽开始时悬浮球位置

// MPTA测量相关
const mptaMeasurements = ref([])      // MPTA测量结果
const selectedMPTA = ref(null)        // 当前选中的MPTA测量

// DOM引用
const canvasContainer = ref(null)
const imageCanvas = ref(null)

// 上传相关
const handleFileChange = (file) => {
  console.log('文件选择:', file)
  if (beforeUpload(file.raw)) {
    loadImageToCanvas(file.raw)
  }
}

const handleUploadSuccess = (response, file) => {
  console.log('上传成功:', response, file)
  loadImageToCanvas(file.raw)
}

const handleUploadError = (error) => {
  console.error('上传失败:', error)
}

const beforeUpload = (file) => {
  const isImage = file.type.startsWith('image/')
  if (!isImage) {
    console.error('只能上传图片文件!')
    return false
  }
  const isLt50M = file.size / 1024 / 1024 < 50
  if (!isLt50M) {
    console.error('图片大小不能超过 50MB!')
    return false
  }
  return true
}

const loadImageToCanvas = (file) => {
  const reader = new FileReader()
  reader.onload = (e) => {
    const img = new Image()
    img.onload = () => {
      const canvas = imageCanvas.value
      const ctx = canvas.getContext('2d')

      // 获取容器尺寸
      const containerRect = canvasContainer.value.getBoundingClientRect()
      const containerWidth = containerRect.width - 2 // 减去边框
      const containerHeight = containerRect.height - 2

      // 计算缩放比例以适合容器
      const scaleX = containerWidth / img.width
      const scaleY = containerHeight / img.height
      const scaleToFit = Math.min(scaleX, scaleY, 1) // 不放大，只缩小

      const displayWidth = img.width * scaleToFit
      const displayHeight = img.height * scaleToFit

      // 设置画布尺寸为显示尺寸
      canvas.width = displayWidth
      canvas.height = displayHeight
      canvas.style.width = displayWidth + 'px'
      canvas.style.height = displayHeight + 'px'

      // 存储原始尺寸和图像数据
      imageWidth.value = img.width
      imageHeight.value = img.height

      // 清除画布并绘制图像
      ctx.clearRect(0, 0, displayWidth, displayHeight)
      ctx.drawImage(img, 0, 0, displayWidth, displayHeight)

      // 保存原始图像数据用于调整
      originalImageData.value = ctx.getImageData(0, 0, displayWidth, displayHeight)
      currentImageData.value = ctx.getImageData(0, 0, displayWidth, displayHeight)

      imageLoaded.value = true

      // 重置调整参数
      resetAdjustments()

      // 自动适合窗口大小
      nextTick(() => {
        fitToWindow()
      })

      // 更新全局状态
      store.actions.setCurrentImage({
        file,
        url: e.target.result,
        width: img.width,
        height: img.height,
        loaded: true
      })

      console.log('图像加载成功:', {
        original: { width: img.width, height: img.height },
        display: { width: displayWidth, height: displayHeight },
        scale: scaleToFit
      })
    }
    img.src = e.target.result
  }
  reader.readAsDataURL(file)
}

// 坐标转换工具函数
const convertMouseToCanvas = (event) => {
  if (!imageCanvas.value) return { x: 0, y: 0 }

  const rect = imageCanvas.value.getBoundingClientRect()

  // 直接使用getBoundingClientRect()返回的实际显示尺寸
  // 这已经包含了CSS transform的影响
  const rawX = event.clientX - rect.left
  const rawY = event.clientY - rect.top

  // 获取画布的原始尺寸
  const canvasWidth = imageCanvas.value.width
  const canvasHeight = imageCanvas.value.height

  // 计算从显示尺寸到画布坐标的比例
  const scaleX = canvasWidth / rect.width
  const scaleY = canvasHeight / rect.height

  // 转换为画布坐标
  const x = rawX * scaleX
  const y = rawY * scaleY

  console.log('🎯 坐标转换详情:', {
    鼠标位置: { clientX: event.clientX, clientY: event.clientY },
    画布边界: { left: rect.left, top: rect.top, width: rect.width, height: rect.height },
    相对位置: { rawX, rawY },
    画布尺寸: { canvasWidth, canvasHeight },
    缩放比例: { scaleX: scaleX.toFixed(3), scaleY: scaleY.toFixed(3) },
    最终坐标: { x: x.toFixed(1), y: y.toFixed(1) },
    当前缩放: scale.value + '%'
  })

  return { x, y }
}

// 工具相关
const openFileExplorer = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = (e) => {
    const file = e.target.files[0]
    if (file && beforeUpload(file)) {
      loadImageToCanvas(file)
    }
  }
  input.click()
}

const setTool = (tool) => {
  activeTool.value = tool
  // 手动切换工具时清除之前的工具记录
  previousTool.value = tool
  // 切换工具时清空临时点和选中状态
  tempPoints.value = []
  currentAnnotation.value = null
  isDrawing.value = false
  selectedAnnotation.value = null
  isDragging.value = false

  // 切换工具时清除连接模式相关状态
  if (tool !== 'connect') {
    selectedPoints.value = []
    connectingMode.value = false
  } else {
    connectingMode.value = true
  }

  redrawCanvas()
}

// 清除选中的标记点
const clearSelectedPoints = () => {
  selectedPoints.value = []
  redrawCanvas()
  console.log('已清除选中的标记点')
}

// 检测点击是否命中已有的标记点
const findPointAnnotationAt = (x, y) => {
  const tolerance = 25  // 增大容差范围

  console.log(`🔍 查找点击位置 (${x.toFixed(1)}, ${y.toFixed(1)}) 的标记点，容差: ${tolerance}`)
  console.log(`🔍 当前总标注数: ${annotations.value.length}`)

  // 从后往前查找，优先选择最新的标记点
  for (let i = annotations.value.length - 1; i >= 0; i--) {
    const annotation = annotations.value[i]
    if (annotation.type === 'point' && annotation.points && annotation.points[0]) {
      const point = annotation.points[0]
      const distance = Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2))
      console.log(`🔍 检查标记点 ${i} (ID: ${annotation.id}): 位置(${point.x.toFixed(1)}, ${point.y.toFixed(1)}), 距离: ${distance.toFixed(1)}`)
      if (distance <= tolerance) {
        console.log(`✅ 找到匹配的标记点: ID=${annotation.id}`)
        return annotation
      }
    }
  }
  console.log(`❌ 未找到匹配的标记点`)
  return null
}

// 基于选中的标记点创建线条
const createLineFromPoints = () => {
  if (selectedPoints.value.length !== 2) {
    console.warn('需要选择2个标记点来创建线条')
    return
  }

  const [point1, point2] = selectedPoints.value

  // 输出连接的标记点信息
  console.log('🔗 连接标记点创建线条:')
  console.log('   起点(ID: ' + point1.id + '):', { x: point1.points[0].x.toFixed(1), y: point1.points[0].y.toFixed(1) })
  console.log('   终点(ID: ' + point2.id + '):', { x: point2.points[0].x.toFixed(1), y: point2.points[0].y.toFixed(1) })

  const lineAnnotation = {
    id: Date.now(),
    type: 'line',
    points: [
      { x: point1.points[0].x, y: point1.points[0].y },
      { x: point2.points[0].x, y: point2.points[0].y }
    ],
    color: annotationColor.value,
    lineWidth: lineWidth.value,
    timestamp: new Date(),
    connectedFrom: [point1.id, point2.id]  // 记录连接来源
  }

  // 计算线条长度
  const deltaX = point2.points[0].x - point1.points[0].x
  const deltaY = point2.points[0].y - point1.points[0].y
  const length = Math.sqrt(deltaX * deltaX + deltaY * deltaY)

  console.log('   线条长度:', length.toFixed(1) + 'px')

  annotations.value.push(lineAnnotation)
  selectedPoints.value = []
  redrawCanvas()

  console.log('✅ 连接线条创建完成!')
}

// 基于选中的标记点创建角度
const createAngleFromPoints = () => {
  console.log('🔥 createAngleFromPoints 函数被调用')
  console.log('🔥 当前选中点数量:', selectedPoints.value.length)
  console.log('🔥 选中的点:', selectedPoints.value.map(p => ({ id: p.id, x: p.points[0].x, y: p.points[0].y })))

  if (selectedPoints.value.length !== 3) {
    console.warn('⚠️ 需要选择3个标记点来创建角度，当前有:', selectedPoints.value.length)
    return
  }

  const [point1, vertex, point3] = selectedPoints.value

  // 输出连接的标记点信息
  console.log('🎯 连接标记点创建角度:')
  console.log('   第1个点(ID: ' + point1.id + '):', { x: point1.points[0].x.toFixed(1), y: point1.points[0].y.toFixed(1) })
  console.log('   顶点(ID: ' + vertex.id + '):', { x: vertex.points[0].x.toFixed(1), y: vertex.points[0].y.toFixed(1) })
  console.log('   第3个点(ID: ' + point3.id + '):', { x: point3.points[0].x.toFixed(1), y: point3.points[0].y.toFixed(1) })

  const angleAnnotation = {
    id: Date.now(),
    type: 'angle',
    points: [
      { x: point1.points[0].x, y: point1.points[0].y },
      { x: vertex.points[0].x, y: vertex.points[0].y },
      { x: point3.points[0].x, y: point3.points[0].y }
    ],
    color: annotationColor.value,
    lineWidth: lineWidth.value,
    timestamp: new Date(),
    connectedFrom: [point1.id, vertex.id, point3.id]  // 记录连接来源
  }

  // 计算角度值
  const p1 = angleAnnotation.points[0]
  const v = angleAnnotation.points[1]
  const p3 = angleAnnotation.points[2]

  const angle1 = Math.atan2(p1.y - v.y, p1.x - v.x)
  const angle2 = Math.atan2(p3.y - v.y, p3.x - v.x)
  let angle = Math.abs(angle2 - angle1) * (180 / Math.PI)
  if (angle > 180) angle = 360 - angle

  console.log('   计算角度:', angle.toFixed(1) + '°')
  console.log('🔥 准备添加角度标注到数组，当前数组长度:', annotations.value.length)

  annotations.value.push(angleAnnotation)
  console.log('🔥 角度标注已添加，新数组长度:', annotations.value.length)
  console.log('🔥 添加的角度标注:', angleAnnotation)

  // 删除原来的3个标记点
  const pointIdsToRemove = [point1.id, vertex.id, point3.id]
  console.log('🗑️ 准备删除原始标记点:', pointIdsToRemove)

  annotations.value = annotations.value.filter(annotation => {
    if (annotation.type === 'point' && pointIdsToRemove.includes(annotation.id)) {
      console.log('🗑️ 删除标记点:', annotation.id)
      return false
    }
    return true
  })

  console.log('🗑️ 标记点删除完成，当前标注数量:', annotations.value.length)

  // 自动添加MPTA测量
  addMPTAMeasurement(angleAnnotation)
  console.log('   已自动添加MPTA测量')

  selectedPoints.value = []
  console.log('🔥 已清空选中点')

  console.log('🔥 准备重绘画布')
  redrawCanvas()
  console.log('🔥 画布重绘完成')

  // 自动切换到标点工具
  activeTool.value = 'point'
  console.log('🔄 自动切换到标点工具')

  console.log('✅ 连接角度创建完成!')
}

const clearAnnotations = () => {
  annotations.value = []
  mptaMeasurements.value = []  // 清除MPTA测量
  selectedAnnotation.value = null
  selectedMPTA.value = null
  currentAnnotation.value = null
  tempPoints.value = []
  isDrawing.value = false
  isDragging.value = false
  redrawCanvas()
  console.log('已清除所有标注和MPTA测量')
}

const undoLastAction = () => {
  if (annotations.value.length > 0) {
    const lastAnnotation = annotations.value.pop()
    annotationHistory.value.push(lastAnnotation)
    selectedAnnotation.value = null
    redrawCanvas()
    console.log('已撤销上一个操作')
  }
}

const redoLastAction = () => {
  if (annotationHistory.value.length > 0) {
    const lastHistoryItem = annotationHistory.value.pop()
    annotations.value.push(lastHistoryItem)
    redrawCanvas()
    console.log('已重做上一个操作')
  }
}

const deleteSelectedAnnotation = () => {
  if (selectedAnnotation.value) {
    const index = annotations.value.findIndex(a => a.id === selectedAnnotation.value.id)
    if (index >= 0) {
      const deleted = annotations.value.splice(index, 1)[0]
      annotationHistory.value.push(deleted)
      selectedAnnotation.value = null
      redrawCanvas()
      console.log('已删除选中的标注')
    }
  }
}

// MPTA相关函数
const startMPTAMeasurement = () => {
  // 切换到角度工具来测量MPTA
  activeTool.value = 'angle'
  console.log('开始MPTA测量，请点击三个点来定义角度')
}

// 添加MPTA测量结果
const addMPTAMeasurement = (angleAnnotation) => {
  if (!angleAnnotation || angleAnnotation.type !== 'angle' || angleAnnotation.points.length < 3) {
    console.warn('Invalid angle annotation for MPTA')
    return
  }

  const [p1, vertex, p3] = angleAnnotation.points

  // 计算角度值
  const angle1 = Math.atan2(p1.y - vertex.y, p1.x - vertex.x)
  const angle2 = Math.atan2(p3.y - vertex.y, p3.x - vertex.x)
  let angle = Math.abs(angle2 - angle1) * (180 / Math.PI)
  if (angle > 180) angle = 360 - angle

  const mptaMeasurement = {
    id: Date.now(),
    type: 'mpta',
    points: [...angleAnnotation.points],
    angle: angle,
    timestamp: new Date(),
    color: '#ff6b00'
  }

  mptaMeasurements.value.push(mptaMeasurement)

  // 输出更详细的日志信息
  console.log(`✅ MPTA测量自动添加成功!`)
  console.log(`   角度值: ${angle.toFixed(1)}°`)
  console.log(`   测量ID: ${mptaMeasurement.id}`)
  console.log(`   总数量: ${mptaMeasurements.value.length} 个MPTA测量`)

  return mptaMeasurement
}

// 删除MPTA测量
const deleteMPTA = (mptaId) => {
  const index = mptaMeasurements.value.findIndex(mpta => mpta.id === mptaId)
  if (index >= 0) {
    mptaMeasurements.value.splice(index, 1)
    if (selectedMPTA.value && selectedMPTA.value.id === mptaId) {
      selectedMPTA.value = null
    }
    redrawCanvas()
    console.log('MPTA测量已删除')
  }
}

// 切换显示控制
// 已移除手动控制，默认显示中线

// 重绘画布和所有标注
const redrawCanvas = () => {
  if (!imageCanvas.value || !currentImageData.value) {
    console.log('redrawCanvas: Missing canvas or image data')
    return
  }

  const canvas = imageCanvas.value
  const ctx = canvas.getContext('2d')

  // 先重新应用图像调整（包含标注重绘）
  applyImageAdjustments()

  // 注意：applyImageAdjustments 已经包含了 redrawAnnotationsOnly，
  // 所以不需要在这里重复绘制标注
}

// 绘制单个标注
const drawAnnotation = (ctx, annotation, isTemp = false) => {
  ctx.save()

  const isSelected = selectedAnnotation.value && selectedAnnotation.value.id === annotation.id

  ctx.strokeStyle = annotation.color || annotationColor.value
  ctx.fillStyle = annotation.color || annotationColor.value
  ctx.lineWidth = annotation.lineWidth || lineWidth.value
  ctx.lineCap = 'round'

  if (isTemp) {
    ctx.globalAlpha = 0.7
  }

  // 选中的标注显示高亮效果
  if (isSelected) {
    ctx.strokeStyle = '#00ff00'
    ctx.fillStyle = '#00ff00'
    ctx.lineWidth = (annotation.lineWidth || lineWidth.value) + 2
  }

  switch (annotation.type) {
    case 'point':
      drawPoint(ctx, annotation)
      break
    case 'line':
      drawLine(ctx, annotation)
      break
    case 'angle':
      drawAngle(ctx, annotation)
      break
  }

  // 绘制选中标注的控制点
  if (isSelected) {
    drawControlPoints(ctx, annotation)
  }

  ctx.restore()
}

// 绘制点标注
const drawPoint = (ctx, annotation) => {
  console.log('📍 绘制点标注:', annotation.id, annotation.points)

  if (!annotation || !annotation.points || annotation.points.length < 1) {
    console.warn('⚠️ 无效的点标注数据:', annotation)
    return
  }

  const point = annotation.points[0]
  if (!point || typeof point.x !== 'number' || typeof point.y !== 'number') {
    console.warn('Invalid point annotation:', annotation.points)
    return
  }

  const { x, y } = point
  const radius = 3

  console.log(`📍 开始绘制点: (${x}, ${y}), 半径: ${radius}`)

  // 检查是否为选中的标记点（用于连接模式）
  const isSelectedForConnection = selectedPoints.value.some(p => p.id === annotation.id)

  // 如果是选中的标记点，使用黄色高亮
  if (isSelectedForConnection) {
    console.log('🔆 绘制高亮效果为选中点')
    ctx.save()
    ctx.fillStyle = '#ffeb3b'  // 黄色高亮
    ctx.strokeStyle = '#ff9800' // 橙色边框
    ctx.lineWidth = 3

    // 绘制高亮圓圈
    ctx.beginPath()
    ctx.arc(x, y, radius + 4, 0, 2 * Math.PI)
    ctx.fill()
    ctx.stroke()

    ctx.restore()
  }

  // 绘制主圆点
  console.log('🔴 绘制主圆点')
  ctx.beginPath()
  ctx.arc(x, y, radius, 0, 2 * Math.PI)
  ctx.fill()

  // 绘制十字线
  console.log('➕ 绘制十字线')
  ctx.beginPath()
  ctx.moveTo(x - 8, y)
  ctx.lineTo(x + 8, y)
  ctx.moveTo(x, y - 8)
  ctx.lineTo(x, y + 8)
  ctx.stroke()

  // 显示标签
  if (annotation.label) {
    console.log('🏷️ 绘制标签:', annotation.label)
    ctx.save()
    ctx.fillStyle = '#333'
    ctx.font = '12px Arial'
    ctx.fillText(annotation.label, x + 10, y - 10)
    ctx.restore()
  }

  // 如果是选中的标记点，显示选中数字
  if (isSelectedForConnection) {
    const selectedIndex = selectedPoints.value.findIndex(p => p.id === annotation.id) + 1
    console.log(`🔢 绘制选中数字: ${selectedIndex}`)
    ctx.save()
    ctx.fillStyle = '#ffffff'
    ctx.font = 'bold 12px Arial'
    ctx.textAlign = 'center'
    ctx.fillText(selectedIndex.toString(), x, y + 4)
    ctx.restore()
  }

  console.log('✅ 点标注绘制完成')
}

// 绘制线条标注
const drawLine = (ctx, annotation) => {
  if (!annotation || !annotation.points || annotation.points.length < 2) return

  // 确保最多只有2个点
  const points = annotation.points.slice(0, 2)
  const [start, end] = points

  // 验证点的有效性
  if (!start || !end ||
    typeof start.x !== 'number' || typeof start.y !== 'number' ||
    typeof end.x !== 'number' || typeof end.y !== 'number') {
    console.warn('Invalid line annotation points:', points)
    return
  }

  // 绘制连接线
  ctx.beginPath()
  ctx.moveTo(start.x, start.y)
  ctx.lineTo(end.x, end.y)
  ctx.stroke()

  // 绘制端点
  ctx.beginPath()
  ctx.arc(start.x, start.y, 3, 0, 2 * Math.PI)
  ctx.fill()

  ctx.beginPath()
  ctx.arc(end.x, end.y, 3, 0, 2 * Math.PI)
  ctx.fill()

  // 计算并显示长度
  const length = Math.sqrt(
    Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2)
  )

  const midX = (start.x + end.x) / 2
  const midY = (start.y + end.y) / 2

  ctx.fillStyle = '#333'
  ctx.font = '12px Arial'
  ctx.fillText(`${length.toFixed(1)}px`, midX + 5, midY - 5)
}

// 绘制角度标注
const drawAngle = (ctx, annotation) => {
  if (!annotation || !annotation.points || annotation.points.length < 3) return

  // 确保最多只有3个点
  const points = annotation.points.slice(0, 3)
  const [p1, vertex, p3] = points

  // 验证所有点的有效性
  if (!p1 || !vertex || !p3 ||
    typeof p1.x !== 'number' || typeof p1.y !== 'number' ||
    typeof vertex.x !== 'number' || typeof vertex.y !== 'number' ||
    typeof p3.x !== 'number' || typeof p3.y !== 'number') {
    console.warn('Invalid angle annotation points:', points)
    return
  }

  // 绘制两条连接线：从顶点到两个端点
  ctx.beginPath()
  ctx.moveTo(vertex.x, vertex.y)
  ctx.lineTo(p1.x, p1.y)
  ctx.moveTo(vertex.x, vertex.y)
  ctx.lineTo(p3.x, p3.y)
  ctx.stroke()

  // 绘制角度弧
  const angle1 = Math.atan2(p1.y - vertex.y, p1.x - vertex.x)
  const angle2 = Math.atan2(p3.y - vertex.y, p3.x - vertex.x)
  const arcRadius = 30

  ctx.beginPath()
  ctx.arc(vertex.x, vertex.y, arcRadius, angle1, angle2, false)
  ctx.stroke()

  // 计算角度值
  let angle = Math.abs(angle2 - angle1) * (180 / Math.PI)
  if (angle > 180) angle = 360 - angle

  // 显示角度值
  const labelX = vertex.x + Math.cos((angle1 + angle2) / 2) * (arcRadius + 15)
  const labelY = vertex.y + Math.sin((angle1 + angle2) / 2) * (arcRadius + 15)

  ctx.fillStyle = '#333'
  ctx.font = '12px Arial'
  ctx.fillText(`${angle.toFixed(1)}°`, labelX, labelY)

  // 绘制所有点
  ctx.beginPath()
  ctx.arc(p1.x, p1.y, 3, 0, 2 * Math.PI)
  ctx.fill()

  ctx.beginPath()
  ctx.arc(vertex.x, vertex.y, 3, 0, 2 * Math.PI)
  ctx.fill()

  ctx.beginPath()
  ctx.arc(p3.x, p3.y, 3, 0, 2 * Math.PI)
  ctx.fill()

  // 保存角度值到标注对象
  annotation.angle = angle
}

// 绘制控制点
const drawControlPoints = (ctx, annotation) => {
  console.log('Drawing control points for:', annotation.type, annotation.points)

  ctx.save()
  ctx.fillStyle = '#00ff00'
  ctx.strokeStyle = '#ffffff'
  ctx.lineWidth = 2

  annotation.points.forEach((point, index) => {
    // 根据标注类型限制点数
    let maxPoints = annotation.points.length
    if (annotation.type === 'line' && index >= 2) return  // 线条最多2个点
    if (annotation.type === 'angle' && index >= 3) return  // 角度最多3个点

    if (point && typeof point.x === 'number' && typeof point.y === 'number') {
      console.log(`Drawing control point ${index} at (${point.x}, ${point.y})`)

      ctx.beginPath()
      ctx.arc(point.x, point.y, 8, 0, 2 * Math.PI)  // 增大控制点半径
      ctx.fill()
      ctx.stroke()

      // 显示点的索引
      ctx.fillStyle = '#ffffff'
      ctx.font = '12px Arial'
      ctx.textAlign = 'center'
      ctx.fillText(index.toString(), point.x, point.y + 3)
      ctx.fillStyle = '#00ff00'
    }
  })

  ctx.restore()
}

// 检测点击是否命中标注
const hitTestAnnotation = (x, y, annotation) => {
  const tolerance = 15  // 增加容差范围

  console.log('hitTestAnnotation:', {
    click: { x, y },
    annotation: annotation.type,
    points: annotation.points
  })

  if (!annotation || !annotation.points) {
    console.log('Invalid annotation:', annotation)
    return false
  }

  switch (annotation.type) {
    case 'point':
      if (annotation.points && annotation.points[0]) {
        const point = annotation.points[0]
        if (point && typeof point.x === 'number' && typeof point.y === 'number') {
          const distance = Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2))
          console.log('Point hit test:', { distance, tolerance, hit: distance <= tolerance })
          return distance <= tolerance
        }
      }
      return false

    case 'line':
      if (annotation.points && annotation.points.length >= 2) {
        // 线条只检测前2个点的连线
        const points = annotation.points.slice(0, 2)
        const [start, end] = points
        if (start && end &&
          typeof start.x === 'number' && typeof start.y === 'number' &&
          typeof end.x === 'number' && typeof end.y === 'number') {
          const distance = distanceToLine(x, y, start.x, start.y, end.x, end.y)
          console.log('Line hit test:', { distance, tolerance, hit: distance <= tolerance })
          return distance <= tolerance
        }
      }
      return false

    case 'angle':
      if (annotation.points && annotation.points.length >= 3) {
        // 角度只检测前3个点的连线
        const points = annotation.points.slice(0, 3)
        const [p1, vertex, p3] = points
        if (p1 && vertex && p3 &&
          typeof p1.x === 'number' && typeof p1.y === 'number' &&
          typeof vertex.x === 'number' && typeof vertex.y === 'number' &&
          typeof p3.x === 'number' && typeof p3.y === 'number') {
          const dist1 = distanceToLine(x, y, vertex.x, vertex.y, p1.x, p1.y)
          const dist2 = distanceToLine(x, y, vertex.x, vertex.y, p3.x, p3.y)
          const hit = dist1 <= tolerance || dist2 <= tolerance
          console.log('Angle hit test:', { dist1, dist2, tolerance, hit })
          return hit
        }
      }
      return false

    default:
      console.log('Unknown annotation type:', annotation.type)
      return false
  }
}

// 检测是否点击在控制点上
const hitTestControlPoint = (x, y, annotation) => {
  const tolerance = 10  // 增加容差范围

  console.log('hitTestControlPoint:', {
    click: { x, y },
    annotation: annotation.type,
    points: annotation.points,
    tolerance
  })

  // 根据标注类型限制点数
  let maxPoints = annotation.points.length
  if (annotation.type === 'line') {
    maxPoints = Math.min(2, annotation.points.length)  // 线条最多2个点
  } else if (annotation.type === 'angle') {
    maxPoints = Math.min(3, annotation.points.length)  // 角度最多3个点
  }

  for (let i = 0; i < maxPoints; i++) {
    const point = annotation.points[i]
    if (point && typeof point.x === 'number' && typeof point.y === 'number') {
      const distance = Math.sqrt(Math.pow(x - point.x, 2) + Math.pow(y - point.y, 2))
      console.log(`Control point ${i} distance: ${distance}, tolerance: ${tolerance}`)
      if (distance <= tolerance) {
        console.log(`Hit control point ${i}!`)
        return i
      }
    }
  }
  console.log('No control point hit')
  return -1
}

// 计算点到线段的距离
const distanceToLine = (px, py, x1, y1, x2, y2) => {
  const A = px - x1
  const B = py - y1
  const C = x2 - x1
  const D = y2 - y1

  const dot = A * C + B * D
  const lenSq = C * C + D * D

  if (lenSq === 0) return Math.sqrt(A * A + B * B)

  let param = dot / lenSq

  if (param < 0) {
    return Math.sqrt(A * A + B * B)
  } else if (param > 1) {
    return Math.sqrt(Math.pow(px - x2, 2) + Math.pow(py - y2, 2))
  } else {
    const xx = x1 + param * C
    const yy = y1 + param * D
    return Math.sqrt(Math.pow(px - xx, 2) + Math.pow(py - yy, 2))
  }
}

// 绘制网格
const drawGrid = (ctx, canvas) => {
  ctx.save()
  ctx.strokeStyle = '#e8e8e8'
  ctx.lineWidth = 1
  ctx.globalAlpha = 0.5

  const gridSize = 20
  const width = canvas.width
  const height = canvas.height

  // 绘制垂直线
  for (let x = 0; x <= width; x += gridSize) {
    ctx.beginPath()
    ctx.moveTo(x, 0)
    ctx.lineTo(x, height)
    ctx.stroke()
  }

  // 绘制水平线
  for (let y = 0; y <= height; y += gridSize) {
    ctx.beginPath()
    ctx.moveTo(0, y)
    ctx.lineTo(width, y)
    ctx.stroke()
  }

  ctx.restore()
}

// 绘制中间标线
const drawCenterLine = (ctx, canvas) => {
  ctx.save()

  const centerX = canvas.width / 2

  // 绘制主要的垂直中线
  ctx.strokeStyle = '#00ff00'
  ctx.lineWidth = 2
  ctx.globalAlpha = 0.9

  ctx.beginPath()
  ctx.moveTo(centerX, 0)
  ctx.lineTo(centerX, canvas.height)
  ctx.stroke()

  // 绘制刻度标记
  ctx.strokeStyle = '#00ff00'
  ctx.lineWidth = 1
  ctx.fillStyle = '#00ff00'
  ctx.font = '10px Arial'
  ctx.textAlign = 'left'

  const scaleInterval = 50 // 每50像素一个刻度
  const majorScaleHeight = 15 // 主刻度高度
  const minorScaleHeight = 8  // 次刻度高度

  // 绘制刻度标记
  for (let y = 0; y <= canvas.height; y += scaleInterval / 5) {
    const isMajorScale = (y % scaleInterval) === 0
    const scaleHeight = isMajorScale ? majorScaleHeight : minorScaleHeight

    // 左侧刻度
    ctx.beginPath()
    ctx.moveTo(centerX - scaleHeight / 2, y)
    ctx.lineTo(centerX + scaleHeight / 2, y)
    ctx.stroke()

    // 每100像素显示数字
    if (isMajorScale && y % (scaleInterval * 2) === 0 && y > 0) {
      ctx.fillText(y.toString(), centerX + majorScaleHeight + 2, y + 3)
    }
  }

  // 绘制顶部标签
  ctx.fillStyle = '#00ff00'
  ctx.font = 'bold 12px Arial'
  ctx.textAlign = 'center'
  ctx.fillText('中轴线', centerX, 15)

  ctx.restore()
}

// 绘制刻度标尺（参照医学影像标尺）
const drawRuler = (ctx, canvas) => {
  if (!showRuler.value) return

  ctx.save()

  // 标尺参数
  const rulerWidth = 40
  const rulerX = canvas.width - rulerWidth - 10
  const startY = 50
  const endY = canvas.height - 50
  const rulerHeight = endY - startY

  // 绘制标尺背景
  ctx.fillStyle = 'rgba(0, 0, 0, 0.8)'
  ctx.fillRect(rulerX, startY, rulerWidth, rulerHeight)

  // 绘制标尺边框
  ctx.strokeStyle = '#ffffff'
  ctx.lineWidth = 1
  ctx.strokeRect(rulerX, startY, rulerWidth, rulerHeight)

  // 标尺刻度设置
  const totalLength = 200 // 模拟200mm的长度
  const majorInterval = 10 // 主刻度间隔(10mm)
  const minorInterval = 5  // 次刻度间隔(5mm)
  const pixelsPerMm = rulerHeight / totalLength

  ctx.strokeStyle = '#ffffff'
  ctx.fillStyle = '#ffffff'
  ctx.font = '10px Arial'
  ctx.textAlign = 'right'

  // 绘制刻度线
  for (let mm = 0; mm <= totalLength; mm += minorInterval) {
    const y = startY + (mm * pixelsPerMm)
    const isMajor = (mm % majorInterval) === 0
    const lineLength = isMajor ? 15 : 8

    ctx.beginPath()
    ctx.moveTo(rulerX + rulerWidth - lineLength, y)
    ctx.lineTo(rulerX + rulerWidth, y)
    ctx.stroke()

    // 显示主刻度数字
    if (isMajor && mm % (majorInterval * 2) === 0) {
      const label = (totalLength - mm).toString()
      ctx.fillText(label, rulerX + rulerWidth - 18, y + 3)
    }
  }

  // 绘制单位标签
  ctx.font = 'bold 11px Arial'
  ctx.textAlign = 'center'
  ctx.fillText('mm', rulerX + rulerWidth / 2, startY - 5)

  ctx.restore()
}

// 绘制MPTA测量
const drawMPTAMeasurements = (ctx) => {
  if (!mptaMeasurements.value.length) return

  ctx.save()

  mptaMeasurements.value.forEach((mpta, index) => {
    if (!mpta.points || mpta.points.length < 3) return

    const [p1, vertex, p3] = mpta.points
    if (!p1 || !vertex || !p3) return

    // 绘制MPTA角度线
    ctx.strokeStyle = '#ff6b00'
    ctx.lineWidth = 3
    ctx.beginPath()
    ctx.moveTo(vertex.x, vertex.y)
    ctx.lineTo(p1.x, p1.y)
    ctx.moveTo(vertex.x, vertex.y)
    ctx.lineTo(p3.x, p3.y)
    ctx.stroke()

    // 绘制角度弧
    const angle1 = Math.atan2(p1.y - vertex.y, p1.x - vertex.x)
    const angle2 = Math.atan2(p3.y - vertex.y, p3.x - vertex.x)
    const arcRadius = 40

    ctx.beginPath()
    ctx.arc(vertex.x, vertex.y, arcRadius, angle1, angle2, false)
    ctx.stroke()

    // 计算角度值
    let angle = Math.abs(angle2 - angle1) * (180 / Math.PI)
    if (angle > 180) angle = 360 - angle

    // 显示MPTA标签和数值
    const labelX = vertex.x + Math.cos((angle1 + angle2) / 2) * (arcRadius + 25)
    const labelY = vertex.y + Math.sin((angle1 + angle2) / 2) * (arcRadius + 25)

    ctx.fillStyle = '#ff6b00'
    ctx.font = 'bold 14px Arial'
    ctx.fillText(`MPTA: ${angle.toFixed(1)}°`, labelX, labelY)

    // 绘制控制点
    if (selectedMPTA.value && selectedMPTA.value.id === mpta.id) {
      ctx.fillStyle = '#ff6b00'
      ctx.strokeStyle = '#ffffff'
      ctx.lineWidth = 2

      mpta.points.forEach((point, pointIndex) => {
        if (point && typeof point.x === 'number' && typeof point.y === 'number') {
          ctx.beginPath()
          ctx.arc(point.x, point.y, 8, 0, 2 * Math.PI)
          ctx.fill()
          ctx.stroke()
        }
      })
    }
  })

  ctx.restore()
}

const resetAdjustments = () => {
  brightness.value = 0
  contrast.value = 0
  saturation.value = 0
  gamma.value = 0
  scale.value = 100
  rotation.value = 0
  flipHorizontal.value = false
  flipVertical.value = false

  // 清除所有标注和MPTA测量
  annotations.value = []
  mptaMeasurements.value = []
  selectedAnnotation.value = null
  selectedMPTA.value = null
  currentAnnotation.value = null
  tempPoints.value = []
  isDrawing.value = false
  isDragging.value = false
  dragStartPoint.value = null
  dragPointIndex.value = -1
  frozenPoints.value = []
  annotationHistory.value = []

  if (imageLoaded.value) {
    applyImageAdjustments()
    // 注意：applyImageAdjustments 已经包含了 redrawAnnotationsOnly，所以不需要重复调用
  }

  console.log('已重置所有调整参数并清除所有标注和MPTA测量')
}

const applyImageAdjustments = () => {
  if (!originalImageData.value || !imageCanvas.value) return

  const canvas = imageCanvas.value
  const ctx = canvas.getContext('2d')
  const imageData = ctx.createImageData(originalImageData.value)
  const data = imageData.data
  const originalData = originalImageData.value.data

  // 计算调整参数
  const brightnessAdjust = brightness.value * 2.55 // 转换为0-255范围
  const contrastAdjust = (contrast.value + 100) / 100 // 转换为倍数
  const saturationAdjust = (saturation.value + 100) / 100
  const gammaAdjust = gamma.value / 100 + 1

  // 应用像素级调整
  for (let i = 0; i < originalData.length; i += 4) {
    let r = originalData[i]
    let g = originalData[i + 1]
    let b = originalData[i + 2]
    const a = originalData[i + 3]

    // 亮度调整
    r = Math.max(0, Math.min(255, r + brightnessAdjust))
    g = Math.max(0, Math.min(255, g + brightnessAdjust))
    b = Math.max(0, Math.min(255, b + brightnessAdjust))

    // 对比度调整
    r = Math.max(0, Math.min(255, (r - 128) * contrastAdjust + 128))
    g = Math.max(0, Math.min(255, (g - 128) * contrastAdjust + 128))
    b = Math.max(0, Math.min(255, (b - 128) * contrastAdjust + 128))

    // 饱和度调整
    const gray = 0.299 * r + 0.587 * g + 0.114 * b
    r = Math.max(0, Math.min(255, gray + (r - gray) * saturationAdjust))
    g = Math.max(0, Math.min(255, gray + (g - gray) * saturationAdjust))
    b = Math.max(0, Math.min(255, gray + (b - gray) * saturationAdjust))

    // 伽马校正
    r = Math.max(0, Math.min(255, 255 * Math.pow(r / 255, 1 / gammaAdjust)))
    g = Math.max(0, Math.min(255, 255 * Math.pow(g / 255, 1 / gammaAdjust)))
    b = Math.max(0, Math.min(255, 255 * Math.pow(b / 255, 1 / gammaAdjust)))

    data[i] = r
    data[i + 1] = g
    data[i + 2] = b
    data[i + 3] = a
  }

  // 清空画布
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  // 保存当前变换状态
  ctx.save()

  // 设置变换中心点
  const centerX = canvas.width / 2
  const centerY = canvas.height / 2
  ctx.translate(centerX, centerY)

  // 应用旋转
  if (rotation.value !== 0) {
    ctx.rotate((rotation.value * Math.PI) / 180)
  }

  // 应用翻转
  const scaleX = flipHorizontal.value ? -1 : 1
  const scaleY = flipVertical.value ? -1 : 1
  ctx.scale(scaleX, scaleY)

  // 将图像数据绘制到临时画布
  const tempCanvas = document.createElement('canvas')
  tempCanvas.width = canvas.width
  tempCanvas.height = canvas.height
  const tempCtx = tempCanvas.getContext('2d')
  tempCtx.putImageData(imageData, 0, 0)

  // 绘制到主画布
  ctx.drawImage(tempCanvas, -canvas.width / 2, -canvas.height / 2)

  // 恢复变换状态
  ctx.restore()

  // 更新当前图像数据
  currentImageData.value = ctx.getImageData(0, 0, canvas.width, canvas.height)

  // 重要：在图像调整后立即重绘所有标注，保留标注信息
  redrawAnnotationsOnly()
}

// 专门用于重绘标注的函数，不影响图像调整
const redrawAnnotationsOnly = () => {
  if (!imageCanvas.value || !currentImageData.value) return

  const canvas = imageCanvas.value
  const ctx = canvas.getContext('2d')

  // 绘制网格（如果启用）
  if (showGrid.value) {
    drawGrid(ctx, canvas)
  }

  // 绘制中间标线（如果启用）
  if (showCenterLine.value) {
    drawCenterLine(ctx, canvas)
  }

  console.log('redrawAnnotationsOnly: Drawing annotations:', annotations.value.length)
  console.log('显示设置 - showMeasurements:', showMeasurements.value)
  console.log('标注列表:', annotations.value.map(a => ({ id: a.id, type: a.type, points: a.points.length })))

  // 绘制所有标注（总是显示，不受showMeasurements控制）
  annotations.value.forEach((annotation, index) => {
    console.log(`Drawing annotation ${index}:`, annotation.type, annotation.points)
    try {
      drawAnnotation(ctx, annotation)
    } catch (error) {
      console.error(`Error drawing annotation ${index}:`, error, annotation)
    }
  })

  // 绘制MPTA测量（如果启用）
  if (showMPTA.value && mptaMeasurements.value.length > 0) {
    drawMPTAMeasurements(ctx)
  }

  // 绘制临时标注（正在绘制中的）
  if (currentAnnotation.value) {
    console.log('Drawing current annotation:', currentAnnotation.value)
    try {
      drawAnnotation(ctx, currentAnnotation.value, true)
    } catch (error) {
      console.error('Error drawing current annotation:', error, currentAnnotation.value)
    }
  }

  // 特别处理角度绘制时的临时点显示
  if (activeTool.value === 'angle' && currentAnnotation.value && currentAnnotation.value.type === 'angle') {
    console.log('🎯 绘制角度临时点:', currentAnnotation.value.points.length)

    // 绘制已经点击的每个点
    currentAnnotation.value.points.forEach((point, index) => {
      if (point && typeof point.x === 'number' && typeof point.y === 'number') {
        ctx.save()

        // 设置临时点的样式
        ctx.fillStyle = '#ff4444'  // 红色临时点
        ctx.strokeStyle = '#ffffff'
        ctx.lineWidth = 2

        // 绘制临时点
        ctx.beginPath()
        ctx.arc(point.x, point.y, 4, 0, 2 * Math.PI)
        ctx.fill()
        ctx.stroke()

        // 绘制点的标识
        ctx.fillStyle = '#ffffff'
        ctx.font = 'bold 12px Arial'
        ctx.textAlign = 'center'
        const label = index === 0 ? '1' : index === 1 ? '顶' : '3'
        ctx.fillText(label, point.x, point.y + 3)

        console.log(`   临时点${index + 1}: (${point.x.toFixed(1)}, ${point.y.toFixed(1)}) - ${label}`)

        ctx.restore()
      }
    })

    // 如果有两个点，绘制第一条线
    if (currentAnnotation.value.points.length >= 2) {
      const [p1, vertex] = currentAnnotation.value.points
      ctx.save()
      ctx.strokeStyle = '#ff4444'
      ctx.lineWidth = 2
      ctx.setLineDash([5, 5])  // 虚线

      ctx.beginPath()
      ctx.moveTo(vertex.x, vertex.y)
      ctx.lineTo(p1.x, p1.y)
      ctx.stroke()

      console.log('   绘制第一条临时线')
      ctx.restore()
    }

    // 绘制鼠标预览线（跟随鼠标位置）
    const points = currentAnnotation.value.points
    if (points.length === 1 && mouseX.value && mouseY.value) {
      // 第一条预览线（从第一个点到鼠标）
      ctx.save()
      ctx.strokeStyle = '#ff8888'
      ctx.lineWidth = 1
      ctx.setLineDash([3, 3])

      ctx.beginPath()
      ctx.moveTo(points[0].x, points[0].y)
      ctx.lineTo(mouseX.value, mouseY.value)
      ctx.stroke()

      console.log('   绘制第一条预览线到鼠标')
      ctx.restore()
    } else if (points.length === 2 && mouseX.value && mouseY.value) {
      // 第二条预览线（从顶点到鼠标）
      ctx.save()
      ctx.strokeStyle = '#ff8888'
      ctx.lineWidth = 1
      ctx.setLineDash([3, 3])

      ctx.beginPath()
      ctx.moveTo(points[1].x, points[1].y)  // 从顶点开始
      ctx.lineTo(mouseX.value, mouseY.value)
      ctx.stroke()

      console.log('   绘制第二条预览线到鼠标')
      ctx.restore()
    }
  }

  console.log('🎨 绘制完成，共绘制', annotations.value.length, '个标注')
}

const applyScaleAdjustment = () => {
  if (!imageCanvas.value) return

  const canvas = imageCanvas.value
  const scaleRatio = scale.value / 100

  console.log('applyScaleAdjustment:', {
    scale: scale.value,
    scaleRatio: scaleRatio,
    canvasSize: { width: canvas.width, height: canvas.height }
  })

  // 设置变换样式，只应用缩放，不影响Canvas内部的旋转
  canvas.style.transform = `scale(${scaleRatio})`
  canvas.style.transformOrigin = 'center center'

  // 确保容器显示状态正确
  const container = canvasContainer.value
  if (container) {
    container.style.display = 'flex'
    container.style.justifyContent = 'center'
    container.style.alignItems = 'center'
    container.style.overflow = 'hidden'
  }
}

const saveAdjustedImage = () => {
  if (!imageCanvas.value) return

  const canvas = imageCanvas.value
  const link = document.createElement('a')
  link.download = 'adjusted_image.png'
  link.href = canvas.toDataURL()
  link.click()

  console.log('已保存调整后的图像')
}

// 导出标注数据
const exportAnnotations = () => {
  const exportData = {
    image: {
      width: imageWidth.value,
      height: imageHeight.value,
      timestamp: new Date()
    },
    annotations: annotations.value.map(annotation => ({
      ...annotation,
      measurements: getMeasurements(annotation)
    }))
  }

  const blob = new Blob([JSON.stringify(exportData, null, 2)], {
    type: 'application/json'
  })

  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `annotations_${new Date().toISOString().slice(0, 10)}.json`
  link.click()

  console.log('标注数据已导出')
}

// 获取标注的测量数据
const getMeasurements = (annotation) => {
  switch (annotation.type) {
    case 'line':
      if (annotation.points.length >= 2) {
        const [start, end] = annotation.points
        const length = Math.sqrt(
          Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2)
        )
        return { length: length.toFixed(2) }
      }
      break
    case 'angle':
      if (annotation.angle) {
        return { angle: annotation.angle.toFixed(2) }
      }
      break
    case 'point':
      return {
        coordinates: annotation.points[0]
      }
  }
  return null
}

// 查看器控制
const fitToWindow = () => {
  if (!imageCanvas.value || !imageLoaded.value || !canvasContainer.value) {
    console.log('fitToWindow: Missing required elements')
    return
  }

  const canvas = imageCanvas.value
  const containerRect = canvasContainer.value.getBoundingClientRect()
  const containerWidth = containerRect.width - 40 // 减去边距
  const containerHeight = containerRect.height - 40

  // 获取画布的实际尺寸（不含缩放）
  const canvasWidth = canvas.width
  const canvasHeight = canvas.height

  console.log('fitToWindow 计算:', {
    container: { width: containerWidth, height: containerHeight },
    canvas: { width: canvasWidth, height: canvasHeight },
    currentScale: scale.value
  })

  // 计算缩放比例以适合容器
  const scaleX = containerWidth / canvasWidth
  const scaleY = containerHeight / canvasHeight
  const fitScale = Math.min(scaleX, scaleY) * 100 // 转换为百分比

  // 限制缩放范围
  const newScale = Math.round(Math.max(10, Math.min(500, fitScale)))

  console.log('计算结果:', {
    scaleX: scaleX.toFixed(3),
    scaleY: scaleY.toFixed(3),
    fitScale: fitScale.toFixed(1),
    newScale
  })

  scale.value = newScale
  applyScaleAdjustment()
}

const actualSize = () => {
  scale.value = 100
  applyScaleAdjustment()
}

const rotateLeft = () => {
  rotation.value = rotation.value - 15
  // 保持在-180到180范围内
  if (rotation.value < -180) {
    rotation.value = rotation.value + 360
  }
  applyImageAdjustments()
  console.log('向左旋转到:', rotation.value, '度')
}

const rotateRight = () => {
  rotation.value = rotation.value + 15
  // 保持在-180到180范围内
  if (rotation.value > 180) {
    rotation.value = rotation.value - 360
  }
  applyImageAdjustments()
  console.log('向右旋转到:', rotation.value, '度')
}

// 键盘事件处理
const handleKeydown = (event) => {
  // 只在图像已加载时响应键盘事件
  if (!imageLoaded.value) return

  switch (event.key) {
    case 'ArrowLeft':
      event.preventDefault()
      rotation.value = rotation.value - 1
      // 保持在-180到180范围内
      if (rotation.value < -180) {
        rotation.value = rotation.value + 360
      }
      applyImageAdjustments()
      break
    case 'ArrowRight':
      event.preventDefault()
      rotation.value = rotation.value + 1
      // 保持在-180到180范围内
      if (rotation.value > 180) {
        rotation.value = rotation.value - 360
      }
      applyImageAdjustments()
      break
  }
}

const applyPreset = (preset) => {
  switch (preset) {
    case 'bone':
      brightness.value = 10
      contrast.value = 30
      saturation.value = -20
      gamma.value = 20
      break
    case 'soft':
      brightness.value = -5
      contrast.value = 15
      saturation.value = 10
      gamma.value = -10
      break
    case 'enhance':
      brightness.value = 15
      contrast.value = 40
      saturation.value = 20
      gamma.value = 30
      break
  }
  applyImageAdjustments()
}

// 悬浮调整球控制
const toggleAdjustment = () => {
  // 如果刚刚完成拖拽，不执行切换操作
  if (dragHappened.value) {
    dragHappened.value = false
    return
  }
  adjustmentExpanded.value = !adjustmentExpanded.value
}

// 初始化悬浮球位置在右上角
const initFloatBallPosition = () => {
  floatBallPosition.value = {
    x: window.innerWidth - 100, // 距离右边界100px
    y: 20 // 距离上边界20px
  }
}

// 悬浮球拖拽功能
const startDragFloatBall = (event) => {
  // 防止事件冒泡，避免触发切换
  event.stopPropagation()

  floatBallDragging.value = true
  dragHappened.value = false // 重置拖拽标记
  dragStartPos.value = {
    x: event.clientX,
    y: event.clientY
  }
  dragStartBallPos.value = {
    x: floatBallPosition.value.x,
    y: floatBallPosition.value.y
  }

  // 添加全局鼠标事件监听
  document.addEventListener('mousemove', dragFloatBall)
  document.addEventListener('mouseup', stopDragFloatBall)

  console.log('开始拖拽悬浮球')
}

const dragFloatBall = (event) => {
  if (!floatBallDragging.value) return

  const deltaX = event.clientX - dragStartPos.value.x
  const deltaY = event.clientY - dragStartPos.value.y

  // 如果鼠标移动了一定距离，标记为发生了拖拽
  if (Math.abs(deltaX) > 3 || Math.abs(deltaY) > 3) {
    dragHappened.value = true
  }

  // 计算新位置
  let newX = dragStartBallPos.value.x + deltaX
  let newY = dragStartBallPos.value.y + deltaY

  // 限制在容器范围内（留出一些边距）
  const minX = 10
  const minY = 10
  const maxX = window.innerWidth - 80  // 减去悬浮球宽度
  const maxY = window.innerHeight - 80 // 减去悬浮球高度

  newX = Math.max(minX, Math.min(maxX, newX))
  newY = Math.max(minY, Math.min(maxY, newY))

  floatBallPosition.value = { x: newX, y: newY }
}

const stopDragFloatBall = () => {
  floatBallDragging.value = false

  // 移除全局鼠标事件监听
  document.removeEventListener('mousemove', dragFloatBall)
  document.removeEventListener('mouseup', stopDragFloatBall)

  console.log('结束拖拽悬浮球')
}

// 绘图事件
const startDrawing = (event) => {
  if (!imageLoaded.value) return

  const { x, y } = convertMouseToCanvas(event)

  console.log('Mouse event:', {
    raw: { x: event.clientX, y: event.clientY },
    canvas: { x, y },
    scale: scale.value,
    scaleRatio: scale.value / 100
  })

  // 连接标记点模式处理
  if (activeTool.value === 'connect') {
    console.log(`🔗 智能连接模式激活, 点击位置: (${x.toFixed(1)}, ${y.toFixed(1)})`)
    console.log(`🔗 当前已选中点数量: ${selectedPoints.value.length}`)
    console.log(`🔗 当前标注总数: ${annotations.value.length}`)
    console.log(`🔗 标记点类型标注数: ${annotations.value.filter(a => a.type === 'point').length}`)

    // 检测是否点击在标记点上
    const pointAnnotation = findPointAnnotationAt(x, y)

    if (pointAnnotation) {
      console.log(`🎯 发现标记点: ID=${pointAnnotation.id}, 位置:(${pointAnnotation.points[0].x.toFixed(1)}, ${pointAnnotation.points[0].y.toFixed(1)})`)

      // 检查是否已经选中这个点
      const alreadySelected = selectedPoints.value.some(p => p.id === pointAnnotation.id)

      if (!alreadySelected) {
        selectedPoints.value.push(pointAnnotation)
        const selectedCount = selectedPoints.value.length

        console.log(`✅ 选中标记点: ID=${pointAnnotation.id}`)
        console.log(`   当前选择数量: ${selectedCount}`)

        // 显示所有已选择的点，根据数量判断角色
        selectedPoints.value.forEach((p, index) => {
          let role = ''
          if (selectedCount === 2) {
            role = index === 0 ? '起点' : '终点'
          } else if (selectedCount >= 3) {
            role = index === 0 ? '第1个点' : index === 1 ? '顶点' : '第3个点'
          } else {
            role = `点${index + 1}`
          }
          console.log(`   ${role}: ID=${p.id}, 位置:(${p.points[0].x.toFixed(1)}, ${p.points[0].y.toFixed(1)})`)
        })

        // 立即重绘显示选中状态
        redrawCanvas()

        // 智能判断：优先3个点创建角度，2个点等待第3个点
        if (selectedPoints.value.length === 3) {
          console.log('🔗 已选择3个点，自动创建角度...')
          console.log('🔗 即将调用 createAngleFromPoints 函数')
          console.log('🔗 当前时间戳:', Date.now())

          // 立即执行角度创建，无需延迟
          console.log('🔗 立即执行 createAngleFromPoints')
          createAngleFromPoints()
          console.log('🔗 createAngleFromPoints 函数调用完成')

          // 确保选中点被清除并重绘
          console.log('🔗 确保清除选中点状态')
          selectedPoints.value = []
          redrawCanvas()
        } else if (selectedPoints.value.length === 2) {
          console.log('🔗 已选择2个点，等待第3个点来创建角度...')
          console.log('🔗 当前选中的点:', selectedPoints.value.map(p => `ID=${p.id}, 位置:(${p.x?.toFixed(1) || 'N/A'}, ${p.y?.toFixed(1) || 'N/A'})`))
          console.log('🔗 提示：再点击一个标记点将自动创建角度')
        } else if (selectedPoints.value.length === 1) {
          console.log('🔗 已选择1个点，继续选择第2个和第3个点...')
        }
      } else {
        console.log('⚠️ 该标记点已被选中: ID=' + pointAnnotation.id)
      }
    } else {
      console.log('❌ 未检测到标记点，请点击有效的标记点')
      console.log('❌ 点击位置详情:', {
        坐标: `(${x.toFixed(1)}, ${y.toFixed(1)})`,
        总标注数: annotations.value.length,
        标记点数: annotations.value.filter(a => a.type === 'point').length
      })

      // 显示所有现有标记点的位置，帮助调试
      annotations.value.filter(a => a.type === 'point').forEach((point, index) => {
        const p = point.points[0]
        const distance = Math.sqrt(Math.pow(x - p.x, 2) + Math.pow(y - p.y, 2))
        console.log(`   标记点${index}: ID=${point.id}, 位置:(${p.x.toFixed(1)}, ${p.y.toFixed(1)}), 距离:${distance.toFixed(1)}`)
      })
    }
    return
  }

  // 智能选择：无论当前什么工具，都先检测是否点击在标注上
  let foundAnnotation = null
  let controlPointIndex = -1

  console.log('🔍 开始检测鼠标点击位置:', { x, y })
  console.log('🔍 当前已选中标注:', selectedAnnotation.value ? selectedAnnotation.value.type : 'null')
  console.log('🔍 总标注数量:', annotations.value.length)

  // 优先检测所有标注的控制点（无论是否已选中）
  for (let i = annotations.value.length - 1; i >= 0; i--) {
    const annotation = annotations.value[i]
    console.log(`🔍 检测标注 ${i} (${annotation.type}) 的控制点`)
    const hitResult = hitTestControlPoint(x, y, annotation)
    console.log(`🔍 标注 ${i} hitTestControlPoint 返回值:`, hitResult)

    if (hitResult >= 0) {
      foundAnnotation = annotation
      controlPointIndex = hitResult
      console.log(`✅ 命中控制点! 标注 ${i}, 控制点 ${controlPointIndex}`)
      break
    }
  }

  // 如果没有命中任何控制点，检测是否命中标注整体
  if (!foundAnnotation) {
    console.log('🔍 没有命中控制点，检测标注整体...')
    for (let i = annotations.value.length - 1; i >= 0; i--) {
      console.log(`🔍 检测标注整体 ${i}:`, annotations.value[i])
      if (hitTestAnnotation(x, y, annotations.value[i])) {
        foundAnnotation = annotations.value[i]
        controlPointIndex = -1  // 整体拖拽
        console.log('✅ 命中标注整体:', i, foundAnnotation)
        break
      }
    }
  }

  // 如果找到标注，自动切换到选择模式
  if (foundAnnotation) {
    console.log(`🎯 自动切换到选择模式，选中标注: ${foundAnnotation.type}`)
    console.log(`🕹️ 控制点索引: ${controlPointIndex}, 标注ID: ${foundAnnotation.id}`)

    // 保存当前工具状态，然后切换到选择模式
    if (activeTool.value !== 'select') {
      previousTool.value = activeTool.value
    }
    activeTool.value = 'select'

    selectedAnnotation.value = foundAnnotation
    isDragging.value = true
    dragStartPoint.value = { x, y }

    console.log(`🕹️ 设置 dragPointIndex 为: ${controlPointIndex} (类型: ${typeof controlPointIndex})`)
    dragPointIndex.value = controlPointIndex
    console.log(`🕹️ 验证 dragPointIndex.value: ${dragPointIndex.value} (类型: ${typeof dragPointIndex.value})`)

    // 立即验证赋值是否成功
    if (dragPointIndex.value !== controlPointIndex) {
      console.error('❌ dragPointIndex 赋值失败!', {
        expected: controlPointIndex,
        actual: dragPointIndex.value
      })
    } else {
      console.log('✅ dragPointIndex 赋值成功!')
    }

    // 如果是控制点拖拽，冻结其他点的位置
    if (controlPointIndex >= 0) {
      frozenPoints.value = []
      foundAnnotation.points.forEach((p, i) => {
        if (i !== controlPointIndex) {
          frozenPoints.value.push({
            index: i,
            x: p.x,
            y: p.y
          })
        }
      })
      console.log(`🔒 冻结其他点位置:`, frozenPoints.value)
    }

    if (controlPointIndex >= 0) {
      console.log(`🔄 开始拖拽控制点 ${controlPointIndex} 于位置 (${x}, ${y})`)
    } else {
      console.log(`🔄 开始拖拽整个标注 于位置 (${x}, ${y})`)
    }

    redrawCanvas()
    return
  }

  // 如果是原来的选择模式且没有找到标注，清除选择
  if (activeTool.value === 'select') {
    selectedAnnotation.value = null
    console.log('No annotation found, cleared selection')

    // 如果是自动切换到的选择模式，切换回原先的工具
    if (previousTool.value) {
      activeTool.value = previousTool.value
      console.log(`点击空白区域，切换回原先的工具: ${previousTool.value}`)

      // 确保清除选中状态，让所有标注恢复正常显示
      selectedAnnotation.value = null

      // 继续执行绘制逻辑
      isDrawing.value = true
      switch (activeTool.value) {
        case 'point':
          createPointAnnotation(x, y)
          break
        case 'line':
          startLineAnnotation(x, y)
          break
        case 'angle':
          startAngleAnnotation(x, y)
          break
      }
    }

    redrawCanvas()
    return
  }

  // 执行原有的绘制逻辑
  isDrawing.value = true

  switch (activeTool.value) {
    case 'point':
      createPointAnnotation(x, y)
      break
    case 'line':
      startLineAnnotation(x, y)
      break
    case 'angle':
      startAngleAnnotation(x, y)
      break
  }
}

const drawing = (event) => {
  const { x, y } = convertMouseToCanvas(event)
  mouseX.value = Math.round(x)
  mouseY.value = Math.round(y)

  // 处理拖拽操作
  if (isDragging.value && selectedAnnotation.value && dragStartPoint.value) {
    console.log(`🔄 进入拖拽处理， dragPointIndex.value = ${dragPointIndex.value}`)

    // 明确区分控制点拖拽和整体拖拽
    if (dragPointIndex.value >= 0) {
      // 只处理单个控制点拖拽，绝对不影响其他点
      console.log(`🎯 单个控制点拖拽模式: 点${dragPointIndex.value}`)

      // 验证是否在有效范围内
      let isValidIndex = false
      if (selectedAnnotation.value.type === 'line' && dragPointIndex.value < 2) {
        isValidIndex = true
      } else if (selectedAnnotation.value.type === 'angle' && dragPointIndex.value < 3) {
        isValidIndex = true
      } else if (selectedAnnotation.value.type === 'point' && dragPointIndex.value < 1) {
        isValidIndex = true
      }

      if (isValidIndex) {
        const point = selectedAnnotation.value.points[dragPointIndex.value]
        if (point) {
          console.log(`📍 移动控制点 ${dragPointIndex.value}: (${point.x}, ${point.y}) -> (${x}, ${y})`)

          // 只更新当前拖拽的点
          point.x = x
          point.y = y

          // 强制恢复所有冻结点的位置
          frozenPoints.value.forEach(frozen => {
            const frozenPoint = selectedAnnotation.value.points[frozen.index]
            if (frozenPoint) {
              if (frozenPoint.x !== frozen.x || frozenPoint.y !== frozen.y) {
                console.warn(`⚠️ 强制恢复点${frozen.index}: (${frozenPoint.x}, ${frozenPoint.y}) -> (${frozen.x}, ${frozen.y})`)
              }
              frozenPoint.x = frozen.x
              frozenPoint.y = frozen.y
            }
          })

          console.log(`✅ 最终位置:`, selectedAnnotation.value.points.map((p, i) => {
            const status = i === dragPointIndex.value ? '🎯移动' : '🔒固定'
            return `${status}点${i}:(${p.x},${p.y})`
          }).join(' '))
        }
      }
    } else if (dragPointIndex.value === -1) {
      // 只在明确为整体拖拽时才移动所有点
      console.log(`🔄 整体标注拖拽模式`)

      const deltaX = x - dragStartPoint.value.x
      const deltaY = y - dragStartPoint.value.y

      console.log(`🔄 移动整个标注:`, { deltaX, deltaY })

      selectedAnnotation.value.points.forEach((point, index) => {
        if (point) {
          console.log(`  移动点${index}: (${point.x}, ${point.y}) -> (${point.x + deltaX}, ${point.y + deltaY})`)
          point.x += deltaX
          point.y += deltaY
        }
      })
      dragStartPoint.value = { x, y }
    }

    redrawCanvas()
    return
  }

  // 原有的绘制逻辑
  if (!isDrawing.value || !currentAnnotation.value) {
    // 即使不在绘制状态，也要为角度工具提供预览
    if (activeTool.value === 'angle' && currentAnnotation.value && currentAnnotation.value.points.length > 0) {
      // 为角度绘制提供实时预览
      redrawCanvas()
    }
    return
  }

  if (activeTool.value === 'line' && currentAnnotation.value.points.length === 1) {
    // 更新线条的终点，确保第二个点存在
    if (!currentAnnotation.value.points[1]) {
      currentAnnotation.value.points.push({ x, y })
    } else {
      currentAnnotation.value.points[1] = { x, y }
    }
    redrawCanvas()
  }

  // 角度绘制的实时预览逻辑
  if (activeTool.value === 'angle' && currentAnnotation.value && currentAnnotation.value.type === 'angle') {
    // 立即重绘显示实时预览
    redrawCanvas()
  }
}

const stopDrawing = (event) => {
  // 结束拖拽
  if (isDragging.value) {
    isDragging.value = false
    dragStartPoint.value = null
    dragPointIndex.value = -1
    frozenPoints.value = []  // 清理冻结点
    console.log('结束拖拽')

    // 立即清除选中状态，让标注恢复正常显示
    selectedAnnotation.value = null

    // 如果之前是自动切换到选择模式，现在切换回原先的工具
    if (activeTool.value === 'select' && previousTool.value) {
      activeTool.value = previousTool.value
      console.log(`自动切换回原先的工具: ${previousTool.value}`)
    }

    // 重新绘制画布，确保所有标注显示正常颜色
    redrawCanvas()
    return
  }

  if (!isDrawing.value) return

  const { x, y } = convertMouseToCanvas(event)

  switch (activeTool.value) {
    case 'line':
      finishLineAnnotation(x, y)
      break
    case 'angle':
      continueAngleAnnotation(x, y)
      break
  }

  isDrawing.value = false
}

// 创建点标注
const createPointAnnotation = (x, y) => {
  console.log('🎯 创建新标记点:', { x: x.toFixed(1), y: y.toFixed(1) })

  const annotation = {
    id: Date.now(),
    type: 'point',
    points: [{ x, y }],
    color: annotationColor.value,
    lineWidth: lineWidth.value,
    label: `点${annotations.value.length + 1}`,
    timestamp: new Date()
  }

  annotations.value.push(annotation)

  console.log('✅ 标记点创建完成: ID=' + annotation.id + ', 标签=' + annotation.label)

  redrawCanvas()
  isDrawing.value = false
}

// 开始线条标注
const startLineAnnotation = (x, y) => {
  // 确保坐标是有效的数字
  if (typeof x !== 'number' || typeof y !== 'number') {
    console.warn('Invalid coordinates for line annotation:', { x, y })
    return
  }

  currentAnnotation.value = {
    id: Date.now(),
    type: 'line',
    points: [{ x, y }], // 只初始化第一个点
    color: annotationColor.value,
    lineWidth: lineWidth.value,
    timestamp: new Date()
  }
}

// 完成线条标注
const finishLineAnnotation = (x, y) => {
  if (currentAnnotation.value && currentAnnotation.value.points && currentAnnotation.value.points.length >= 1) {
    // 确保第二个点存在并且格式正确
    if (!currentAnnotation.value.points[1]) {
      currentAnnotation.value.points.push({ x, y })
    } else {
      currentAnnotation.value.points[1] = { x, y }
    }

    // 验证线条数据的完整性
    if (currentAnnotation.value.points.length >= 2 &&
      currentAnnotation.value.points[0] &&
      currentAnnotation.value.points[1] &&
      typeof currentAnnotation.value.points[0].x === 'number' &&
      typeof currentAnnotation.value.points[0].y === 'number' &&
      typeof currentAnnotation.value.points[1].x === 'number' &&
      typeof currentAnnotation.value.points[1].y === 'number') {

      annotations.value.push(currentAnnotation.value)
      currentAnnotation.value = null
      redrawCanvas()
    } else {
      console.warn('Invalid line annotation data:', currentAnnotation.value)
      currentAnnotation.value = null
    }
  }
}

// 开始角度标注
const startAngleAnnotation = (x, y) => {
  if (!currentAnnotation.value) {
    // 第一个点
    currentAnnotation.value = {
      id: Date.now(),
      type: 'angle',
      points: [{ x, y }],
      color: annotationColor.value,
      lineWidth: lineWidth.value,
      timestamp: new Date()
    }
    console.log('🎯 角度标注 - 第1个点:', { x: x.toFixed(1), y: y.toFixed(1) })
  } else if (currentAnnotation.value.points.length === 1) {
    // 第二个点（顶点）
    currentAnnotation.value.points.push({ x, y })
    console.log('🎯 角度标注 - 第2个点(顶点):', { x: x.toFixed(1), y: y.toFixed(1) })
  } else if (currentAnnotation.value.points.length === 2) {
    // 第三个点，完成角度标注
    currentAnnotation.value.points.push({ x, y })
    console.log('🎯 角度标注 - 第3个点:', { x: x.toFixed(1), y: y.toFixed(1) })

    const completedAnnotation = { ...currentAnnotation.value }

    // 输出完整的角度信息
    const [p1, vertex, p3] = completedAnnotation.points
    console.log('✅ 角度标注完成!')
    console.log('   第1个点:', { x: p1.x.toFixed(1), y: p1.y.toFixed(1) })
    console.log('   顶点:', { x: vertex.x.toFixed(1), y: vertex.y.toFixed(1) })
    console.log('   第3个点:', { x: p3.x.toFixed(1), y: p3.y.toFixed(1) })

    // 计算角度值
    const angle1 = Math.atan2(p1.y - vertex.y, p1.x - vertex.x)
    const angle2 = Math.atan2(p3.y - vertex.y, p3.x - vertex.x)
    let angle = Math.abs(angle2 - angle1) * (180 / Math.PI)
    if (angle > 180) angle = 360 - angle

    console.log('   计算角度:', angle.toFixed(1) + '°')

    annotations.value.push(completedAnnotation)

    // 直接创建MPTA测量，无需用户确认
    addMPTAMeasurement(completedAnnotation)
    console.log('   已自动添加MPTA测量')

    currentAnnotation.value = null
    redrawCanvas()
  }
}

// 继续角度标注
// 继续角度标注
const continueAngleAnnotation = (x, y) => {
  // 角度标注在startDrawing中处理
  // 这里可以添加一些进度检查的日志
  if (currentAnnotation.value && currentAnnotation.value.type === 'angle') {
    const pointCount = currentAnnotation.value.points.length
    console.log(`🔄 角度标注进度检查: 已有 ${pointCount} 个点, 当前位置: (${x.toFixed(1)}, ${y.toFixed(1)})`)
  }
}

const handleWheel = (event) => {
  // 禁用滚轮缩放功能
  // event.preventDefault()
  // const delta = event.deltaY > 0 ? -10 : 10
  // scale.value = Math.max(10, Math.min(500, scale.value + delta))
}

// 加载测试图像
const loadTestImage = () => {
  const img = new Image()
  img.onload = () => {
    const canvas = imageCanvas.value
    const ctx = canvas.getContext('2d')

    // 获取容器尺寸
    const containerRect = canvasContainer.value.getBoundingClientRect()
    const containerWidth = containerRect.width - 2 // 减去边框
    const containerHeight = containerRect.height - 2

    // 计算缩放比例以适合容器
    const scaleX = containerWidth / img.width
    const scaleY = containerHeight / img.height
    const scaleToFit = Math.min(scaleX, scaleY, 1) // 不放大，只缩小

    const displayWidth = img.width * scaleToFit
    const displayHeight = img.height * scaleToFit

    // 设置画布尺寸为显示尺寸
    canvas.width = displayWidth
    canvas.height = displayHeight
    canvas.style.width = displayWidth + 'px'
    canvas.style.height = displayHeight + 'px'

    // 存储原始尺寸和图像数据
    imageWidth.value = img.width
    imageHeight.value = img.height

    // 清除画布并绘制图像
    ctx.clearRect(0, 0, displayWidth, displayHeight)
    ctx.drawImage(img, 0, 0, displayWidth, displayHeight)

    // 保存原始图像数据用于调整
    originalImageData.value = ctx.getImageData(0, 0, displayWidth, displayHeight)
    currentImageData.value = ctx.getImageData(0, 0, displayWidth, displayHeight)

    imageLoaded.value = true

    // 重置调整参数
    resetAdjustments()

    // 自动适合窗口大小
    nextTick(() => {
      fitToWindow()
    })
  }

  img.onerror = () => {
    console.error('无法加载默认图片: /default.jpeg')
  }

  // 设置图片源为 public 文件夹中的 default.jpeg
  img.src = '/default.jpeg'
}

onMounted(() => {
  // 初始化悬浮球位置
  initFloatBallPosition()

  // 初始化画布
  nextTick(() => {
    if (imageCanvas.value) {
      const canvas = imageCanvas.value
      canvas.width = 800
      canvas.height = 600
    }
  })

  // 监听窗口大小变化
  const handleResize = () => {
    // 重新调整悬浮球位置，确保始终在右上角
    if (!floatBallDragging.value) {
      initFloatBallPosition()
    }

    if (imageLoaded.value) {
      // 延迟执行适合窗口，等待DOM更新
      setTimeout(() => {
        fitToWindow()
      }, 100)
    }
  }

  window.addEventListener('resize', handleResize)

  // 组件销毁时清理监听器
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    // 清理悬浮球拖拽事件
    document.removeEventListener('mousemove', dragFloatBall)
    document.removeEventListener('mouseup', stopDragFloatBall)
  })
})
</script>

<style scoped>
.image-analysis {
  height: 100vh;
  display: flex;
  flex-direction: column;
  padding: 16px;
}

.page-header {
  margin-bottom: 16px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.content-wrapper {
  flex: 1;
  display: flex;
  gap: 16px;
  min-height: 0;
}

.tools-panel {
  width: 240px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.adjustment-panel {
  width: 240px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.tool-card {
  flex-shrink: 0;
}

.card-header {
  font-weight: 500;
  color: #262626;
}

.upload-section {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.quick-actions {
  display: flex;
  gap: 8px;
}

.adjustment-controls {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.control-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.control-group label {
  font-size: 14px;
  color: #595959;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.flip-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preset-buttons {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.preset-buttons .el-button {
  font-size: 12px;
}

.el-button+.el-button {
  margin-left: 0;
}

.adjustment-actions {
  display: flex;
  gap: 8px;
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
  margin-top: 12px;
}

.view-controls,
.rotation-controls {
  display: flex;
  gap: 8px;
}

.adjustment-buttons {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.annotation-tools {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tool-options {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.color-picker,
.line-width {
  display: flex;
  align-items: center;
  gap: 8px;
}

.color-picker label,
.line-width label {
  font-size: 14px;
  color: #595959;
  min-width: 60px;
}

.annotation-info {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  margin: 12px 0;
}

.info-title {
  font-weight: 500;
  margin-bottom: 8px;
  color: #262626;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 13px;
  color: #595959;
}

.current-tool-tip {
  padding: 8px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  margin: 12px 0;
}

.tip-content {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #0050b3;
}

.export-actions {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
  margin-top: 12px;
}

.tool-actions {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.annotation-info {
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
  margin: 12px 0;
}

.info-title {
  font-weight: 500;
  margin-bottom: 8px;
  color: #262626;
}

.info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 4px;
  font-size: 13px;
  color: #595959;
}

.current-tool-tip {
  padding: 8px;
  background: #e6f7ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  margin: 12px 0;
}

.tip-content {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #0050b3;
}

.export-actions {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
  margin-top: 12px;
}

.image-viewer {
  flex: 1;
  min-width: 0;
  margin: 0 8px;
  position: relative;
}

.viewer-card {
  display: flex;
  flex-direction: column;
}

.viewer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.canvas-container {
  flex: 1;
  position: relative;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
  min-height: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.image-canvas {
  cursor: crosshair;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.2s ease;
}

.empty-state {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #8c8c8c;
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.integrated-upload {
  margin: 20px 0;
  max-width: 400px;
}

.integrated-upload .el-upload-dragger {
  width: 100%;
  height: 120px;
}

.test-actions {
  margin-top: 20px;
}

.viewer-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 4px 0;
  font-size: 11px;
  color: #8c8c8c;
  border-top: 1px solid #f0f0f0;
  height: 24px;
  min-height: 24px;
  flex-shrink: 0;
}

:deep(.el-upload-dragger) {
  border: 2px dashed #d9d9d9;
  border-radius: 6px;
  background: #fafafa;
  text-align: center;
  transition: border-color 0.3s ease;
}

:deep(.el-upload-dragger:hover) {
  border-color: #1890ff;
}

:deep(.el-card__body) {
  padding: 12px;
}

/* MPTA测量样式 */
.mpta-controls {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.mpta-actions {
  display: flex;
  gap: 8px;
}

.mpta-list {
  border-top: 1px solid #f0f0f0;
  padding-top: 12px;
}

.mpta-header {
  font-size: 14px;
  font-weight: 500;
  color: #262626;
  margin-bottom: 8px;
}

.mpta-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.mpta-item:hover {
  background: #e6f7ff;
  border-color: #91d5ff;
}

.mpta-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
  box-shadow: 0 0 0 1px rgba(24, 144, 255, 0.2);
}

.mpta-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.mpta-label {
  font-size: 12px;
  color: #8c8c8c;
}

.mpta-value {
  font-size: 16px;
  font-weight: 600;
  color: #ff6b00;
}

.mpta-empty {
  text-align: center;
  padding: 20px;
  color: #8c8c8c;
  font-size: 14px;
}

/* 连接工具样式 */
.connect-tools {
  margin-top: 16px;
}

.connect-tools .el-divider {
  margin: 12px 0;
  font-size: 13px;
  color: #595959;
}

.connect-tip {
  margin-top: 12px;
  padding: 8px;
  background: #f0f8ff;
  border: 1px solid #91d5ff;
  border-radius: 4px;
  font-size: 12px;
}

.connect-tip .tip-content {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #0050b3;
  margin-bottom: 6px;
}

.selected-points {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #1890ff;
  font-weight: 500;
}

/* 悬浮调整球样式 */
.floating-adjustment {
  position: fixed;
  z-index: 9999;
  transition: all 0.3s ease;
}

.floating-adjustment.dragging {
  transition: none;
  z-index: 10002;
}

.float-trigger {
  width: 56px;
  height: 56px;
  background: #1890ff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: move;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.4);
  transition: all 0.3s ease;
  font-size: 20px;
  z-index: 10000;
  position: relative;
  user-select: none;
}

.float-trigger:hover {
  background: #40a9ff;
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(24, 144, 255, 0.5);
}

.floating-adjustment.dragging .float-trigger {
  background: #722ed1;
  transform: scale(1.1);
  box-shadow: 0 8px 20px rgba(114, 46, 209, 0.6);
  cursor: grabbing;
}

.floating-adjustment.expanded .float-trigger {
  background: #722ed1;
}

.adjustment-panel-floating {
  position: absolute;
  top: 70px;
  right: 0;
  width: 320px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  border: 1px solid #e8e8e8;
  max-height: 70vh;
  overflow-y: auto;
  z-index: 10001;
}

.adjustment-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  font-weight: 500;
  color: #262626;
}

.adjustment-panel-floating .adjustment-controls {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.adjustment-panel-floating .control-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.adjustment-panel-floating .control-group label {
  font-size: 14px;
  color: #595959;
  font-weight: 500;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.adjustment-panel-floating .view-controls {
  display: flex;
  gap: 8px;
}

.adjustment-panel-floating .rotation-controls {
  display: flex;
  gap: 8px;
}

.adjustment-panel-floating .flip-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.adjustment-panel-floating .preset-buttons {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.adjustment-panel-floating .preset-buttons .el-button {
  font-size: 12px;
}
</style>
